package com.hzj.controller;

import com.hzj.common.lang.Const;
import com.hzj.common.lang.Result;
import com.hzj.pojo.SysUser;
import com.hzj.service.SysUserService;
import com.hzj.utils.JwtUtils;
import com.hzj.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
public class TestController {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    JwtUtils jwtUtils;


    @PostMapping("/login")
    public Result test(@RequestParam("username") String name ,
                       @RequestParam("password") String password,
                       Model model,
                       HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse)
    {

        SysUser sysUser = sysUserService.getSysUserByName(name);
        String code = httpServletRequest.getParameter("code");
        String key = httpServletRequest.getParameter("token");
        Object validate = redisUtil.hget(Const.CAPTCHA_KEY , key);
        if (!code.equals(validate)) {
            redisUtil.hdel(Const.CAPTCHA_KEY , key);
            return Result.fail("验证码错误");
        }

        if (sysUser != null) {
            if (name.equals(sysUser.getUsername()) && password.equals(sysUser.getPassword())) {
                //登录成功生成jwt
                String jwt = jwtUtils.generateToken(name);
                //System.out.println(jwt);
                //System.out.println(jwtUtils.getHeader());
                httpServletResponse.setHeader(jwtUtils.getHeader() , jwt);
                redisUtil.hdel(Const.CAPTCHA_KEY , key);
                return Result.succ(sysUser);
            }
            else {
                redisUtil.hdel(Const.CAPTCHA_KEY , key);
                return Result.fail("用户名密码错误");
            }
        }
        redisUtil.hdel(Const.CAPTCHA_KEY , key);
        return Result.fail("用户名不存在");

    }

}
